<script setup>
	import {
		cancelUserOrderAPI,
		refundUserOrderAPI,
		getUserOrderByIdAPI,
		getAllOrderStatusAPI,
		confirmUserOrderAPI,
		orderPayAPI,
	} from '@/services/order'
	import dayjs from 'dayjs';
	import {
		baseUrl
	} from '@/common/api/config.js'
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app'
	import {
		useUserStore
	} from '@/stores/index.js';
	import {
		ref
	} from 'vue'

	/** 订单状态列表 */
	const orderStatusList = ref([])
	// 弹出层组件
	const popup_refund = ref()
	const popup_cancel = ref()
	// 取消原因列表
	const reasonList = ref([
		'菜品无货',
		'不想要了',
		'地址信息填写错误',
		'其它',
	])
	// 退款原因列表
	const reasonList2 = ref([
		'菜品变质',
		'菜品缺斤少两',
		'配送不及时',
		'其它',
	])
	// 订单取消原因
	const reason = ref('')
	// 订单退款原因
	const reason2 = ref('')
	// 复制内容
	const onCopy = (id) => {
		// 设置系统剪贴板的内容
		uni.setClipboardData({
			data: id
		})
	}

	// 获取页面参数
	const orderId = ref("")

	// 获取订单详情
	const order = ref({})

	onLoad(async (params) => {
		orderId.value = params.orderId
		//获取所有订单状态
		const res2 = await getAllOrderStatusAPI()
		orderStatusList.value = res2.data.data
		//根据订单id获取订单详情
		const res = await getUserOrderByIdAPI({
			o_id: params.orderId
		})
		order.value = res.data.data

	})

	// 订单支付
	const onOrderPay = async () => {
		const userStore = useUserStore()
		const payRes = await orderPayAPI({
			o_id: order.value.o_id
		})
		console.log(111111111111, payRes)
		// #ifdef MP-WEIXIN
		// 正式环境支付：1.获取支付订单信息，2.调用微信支付API
		if (payRes.data.code == 200) {
			uni.requestPayment({
				"provider": "wxpay", //支付方式  
				"timeStamp": payRes.data.data.timeStamp, //时间戳
				"nonceStr": payRes.data.data.nonceStr, //随机字符串
				"package": payRes.data.data.package, //接口返回的prepay_id
				"signType": payRes.data.data.signType, //签名算法，需要与后台下单时一致
				"paySign": payRes.data.data.paySign, //签名
				success: function(resSuccess) {
					//触发该success时已经是输入密码支付成功后触发，可做一些页面跳转和成功提示  
					console.log('支付成功', res);
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '支付成功！',
					});
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/order/order'
						})
					}, 1500)
				},
				fail: function(err) {
					//支付失败时出发，比如取消支付、余额不足等
					console.error('支付失败', err);
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '支付失败！',
					});
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/order/order'
						})
					}, 1500)
				}
			});
		} else {
			uni.showToast({
				title: "支付失败！",
				icon: "none"
			})
		}
	}

	// 确认收货
	const onOrderConfirm = (orderId) => {
		// 二次确认弹窗
		uni.showModal({
			content: '为保障您的权益，请收到货并确认无误后，再确认收货',
			confirmColor: '#27BA9B',
			success: async (success) => {
				if (success.confirm) {
					const res = await confirmUserOrderAPI(orderId)
					if (res.data.code == 200) {
						// 轻提示
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '订单已确认',
						});
						setTimeout(function() {
							uni.switchTab({
								url: '/pages/order/order'
							})
						}, 1500)
					
					}else{
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '订单确认失败',
						});
						setTimeout(function() {
							uni.switchTab({
								url: '/pages/order/order'
							})
						}, 1500)
					}
					// 更新订单状态
					// order.value = res.result
				}
			},
		})
	}

	// 取消订单
	const onOrderCancel = async () => {
		// 发送请求
		const res = await cancelUserOrderAPI({
			'orderId': orderId.value,
			'reason': reason.value,
		})
		if (res.data.code == 200) {
			// 关闭弹窗
			popup_cancel.value.close()
			// 轻提示
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '订单取消成功',
			});
			setTimeout(function() {
				uni.switchTab({
					url: '/pages/order/order'
				})
			}, 1500)

		}else{
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '订单取消失败',
			});
			setTimeout(function() {
				uni.switchTab({
					url: '/pages/order/order'
				})
			}, 1500)
		}
		// 更新订单信息
		// order.value = res.result

	}

	// 退款订单
	const onOrderRefund = async () => {
		// 发送请求
		const res = await refundUserOrderAPI({
			'orderId': orderId.value,
			'reason': reason2.value,
			'total': order.value.total_pay * 100,
			'refundAmount': order.value.total_pay * 100
		})
		if (res.data.code == 200) {
			// 关闭弹窗
			popup_refund.value.close()
			if (res.data.status == 'SUCCESS') {
				// 轻提示
				uni.showToast({
					icon: 'none',
					mask: true,
					title: '订单退款成功',
				});
				setTimeout(function() {
					uni.switchTab({
						url: '/pages/order/order'
					})
				}, 1500)
			} else if (res.data.status == 'ABNORMAL' || res.data.status == 'CLOSED') {
				uni.showToast({
					icon: 'none',
					mask: true,
					title: '订单退款失败，请联系食堂工作人员',
				});
				setTimeout(function() {
					uni.switchTab({
						url: '/pages/order/order'
					})
				}, 1500)
			}

		}else{
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '订单退款失败，请联系食堂工作人员',
			});
			setTimeout(function() {
				uni.switchTab({
					url: '/pages/order/order'
				})
			}, 1500)
		}
		// 更新订单信息
		// order.value = res.result
	}

	//计算结束时间
	const computedTime = (o_time) => {
		return dayjs(o_time).add(10, 'minute').format('YYYY-MM-DD HH:mm:ss')
		// const orderFinishTime = dayjs(o_time).add(10,'minute')
		// const now = dayjs()
		// orderFinishTime.diff(now)
	}
</script>

<template>
	<!-- 自定义导航栏: 默认透明不可见, scroll-view 滚动到 50 时展示 -->
	<!--  <view class="navbar" :style="{ paddingTop: safeAreaInsets.top + 'px' }">
    <view class="wrap">
      <navigator
        v-if="pages.length > 1"
        open-type="navigateBack"
        class="back icon-left"
      ></navigator>
      <navigator v-else url="/pages/index/index" open-type="switchTab" class="back icon-home">
      </navigator>
      <view class="title">订单详情</view>
    </view>
  </view> -->
	<scroll-view scroll-y class="viewport">
		<template v-if="order">
			<!-- 订单状态 -->
			<view class="overview">
				<!-- 待付款状态:展示倒计时 -->
				<template v-if="order.o_status == '待付款'">
					<view class="status icon-clock">等待付款</view>
					<view class="tips_order">
						<text class="money">应付金额: ¥ {{ order.actually_pay }}</text>
						<text class="time">支付在{{computedTime(order.o_time)}}后将自动关闭</text>
						<!-- <uni-countdown :second="countdown" color="#fff" splitor-color="#fff" :show-day="false"
							:show-colon="false" @timeup="onTimeup" /> -->
					</view>
					<view class="button-group">
						<view class="button" @tap="onOrderPay">去支付</view>
						<view class="button" @tap="popup_cancel.open()">去取消</view>
					</view>
				</template>
				<!-- 其他订单状态:展示再次购买按钮 -->
				<template v-else-if="order.o_status == '已付款'">
					<!-- 订单状态文字 -->
					<view class="status icon-clock">已付款</view>
					<!-- 已付款状态: 展示确认收货按钮 -->
					<view class="button-group">
						<view class="button" @tap="onOrderConfirm">去确认</view>
						<view class="button" @tap="popup_refund.open()">去退款</view>
					</view>
				</template>
			</view>
			<!-- 配送状态 -->
			<view class="shipment">
				<!-- 用户收货地址 -->
				<view class="locate">
					<view class="user"> {{ order.addressField.a_name }} </view>
					<view class="user">{{ order.addressField.a_tel }} </view>
					<view class="address"> {{ order.addressField.o_address }} </view>
				</view>
			</view>
			<!-- 商品信息 -->
			<view class="goods">
				<view class="item">
					<navigator class="navigator" v-for="item in order.dishList" :key="item.cd_id"
						:url="`/pages/goods/goods?id=${item.cd_id}`" hover-class="none">
						<image class="cover" :src="baseUrl+item.cd_url"></image>
						<view class="meta">
							<view class="name ellipsis">{{ item.cd_name }}</view>
							<view class="price">
								<view class="actual">
									<text class="symbol">¥</text>
									<text>{{ item.cd_price }}</text>
								</view>
							</view>
							<view class="quantity">x{{ item.num }}</view>
						</view>
					</navigator>
					<!-- 待评价状态:展示按钮 -->
					<!-- 					<view class="action" v-if="order.orderState === OrderState.DaiPingJia">
						<view class="button primary">申请售后</view>
						<navigator url="" class="button"> 去评价 </navigator>
					</view> -->
				</view>
				<!-- 合计 -->
				<view class="total">
					<view class="row">
						<view class="text">商品总价: </view>
						<view class="symbol">{{ order.total_pay }}</view>
					</view>
					<view class="row">
						<view class="text">商品数量: </view>
						<view class="symbol">{{ order.dishList.length }}</view>
					</view>
					<view class="row">
						<view class="text">应付金额: </view>
						<view class="symbol primary">{{ order.actually_pay }}</view>
					</view>
				</view>
			</view>

			<!-- 订单信息 -->
			<view class="detail">
				<view class="title">订单信息</view>
				<view class="row">
					<view class="item">
						订单编号: {{ order.o_id }} <text class="copy" @tap="onCopy(order.o_id)">复制</text>
					</view>
					<view class="item">下单时间: {{ order.o_time }}</view>
				</view>
			</view>

			<!-- 底部操作栏 -->
			<view class="toolbar-height"></view>
			<view class="toolbar">
				<!-- 待付款状态:展示支付按钮 -->
				<template v-if="order.o_status == '待付款'">
					<view class="button primary" @tap="onOrderPay"> 去支付 </view>
					<view class="button" @tap="popup_cancel.open()"> 取消订单 </view>
				</template>
				<!-- 其他订单状态:按需展示按钮 -->
				<template v-else-if="order.o_status == '已付款'">
					<!-- 待收货状态: 展示确认收货 -->
					<view class="button primary" @tap="onOrderConfirm(order.o_id)"> 去确认 </view>
					<view class="button" @tap="popup_refund.open()"> 去退款 </view>
					<!-- 待评价状态: 展示去评价 -->
					<!-- <view class="button" v-if="order.o_status === OrderState.DaiPingJia"> 去评价 </view>-->
				</template>
			</view>
		</template>
		<template v-else>
			<!-- 骨架屏组件 -->
			<!--      <PageSkeleton /> -->
		</template>
	</scroll-view>
	<!-- 取消订单弹窗 -->
	<uni-popup ref="popup_cancel" type="bottom" background-color="#fff">
		<view class="popup-root">
			<view class="title">订单取消</view>
			<view class="description">
				<view class="tips">请选择取消订单的原因：</view>
				<view class="cell" v-for="item in reasonList" :key="item" @tap="reason = item">
					<text class="text">{{ item }}</text>
					<text class="icon" :class="{ checked: item === reason }"></text>
				</view>
			</view>
			<view class="footer">
				<view class="button" @tap="popup_cancel.close()">取消</view>
				<view class="button primary" @tap="onOrderCancel">确认</view>
			</view>
		</view>
	</uni-popup>
	<!-- 退款弹窗 -->
	<uni-popup ref="popup_refund" type="bottom" background-color="#fff">
		<view class="popup-root">
			<view class="title">订单退款</view>
			<view class="description">
				<view class="tips">请选择退款订单的原因：</view>
				<view class="cell" v-for="item in reasonList2" :key="item" @tap="reason2 = item">
					<text class="text">{{ item }}</text>
					<text class="icon" :class="{ checked: item === reason2 }"></text>
				</view>
			</view>
			<view class="footer">
				<view class="button" @tap="popup_refund.close()">取消</view>
				<view class="button primary" @tap="onOrderRefund">确认</view>
			</view>
		</view>
	</uni-popup>
</template>

<style lang="scss">
	page {
		display: flex;
		flex-direction: column;
		height: 100%;
		overflow: hidden;
	}

	.viewport {
		background-color: #f7f7f8;
		height: 90vh;
	}

	.overview {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 20rpx;
		line-height: 1;
		padding-bottom: 30rpx;
		color: #fff;
		background-color: red;
		background-size: cover;

		.status {
			font-size: 36rpx;
		}

		.status::before {
			margin-right: 6rpx;
			font-weight: 500;
		}

		.tips_order {
			margin: 30rpx 0;
			display: flex;
			font-size: 14px;
			align-items: center;
			flex-direction: column;

			.money {
				// margin-right: 30rpx;
			}

			.time {
				margin-top: 10px;
			}
		}

		.button-group {
			margin-top: 30rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.button {
			width: 260rpx;
			height: 64rpx;
			margin: 0 10rpx;
			text-align: center;
			line-height: 64rpx;
			font-size: 28rpx;
			color: red;
			border-radius: 68rpx;
			background-color: #fff;
		}
	}

	.shipment {
		line-height: 1.4;
		padding: 0 20rpx;
		margin: 20rpx 20rpx 0;
		border-radius: 10rpx;
		background-color: #fff;

		.locate,
		.item {
			min-height: 120rpx;
			padding: 30rpx 30rpx 25rpx 75rpx;
			background-size: 50rpx;
			background-repeat: no-repeat;
			background-position: 6rpx center;
		}

		.locate {
			background-image: url(http://test.zshawk.top/static/img/order/locate.png);

			.user {
				font-size: 26rpx;
				color: #444;
			}

			.address {
				font-size: 24rpx;
				color: #666;
				word-break: break-all;
			}
		}

		.item {
			background-image: url(http://test.zshawk.top/static/img/order/car.png);
			border-bottom: 1rpx solid #eee;
			position: relative;

			.message {
				font-size: 26rpx;
				color: #444;
			}

			.date {
				font-size: 24rpx;
				color: #666;
			}
		}
	}

	.goods {
		margin: 20rpx 20rpx 0;
		padding: 0 20rpx;
		border-radius: 10rpx;
		background-color: #fff;

		.item {
			padding: 30rpx 0;
			border-bottom: 1rpx solid #eee;

			.navigator {
				display: flex;
				margin: 20rpx 0;
			}

			.cover {
				width: 170rpx;
				height: 170rpx;
				border-radius: 10rpx;
				margin-right: 20rpx;
			}

			.meta {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: center;
				position: relative;
			}

			.name {
				height: 80rpx;
				font-size: 26rpx;
				color: #444;
			}

			.type {
				line-height: 1.8;
				padding: 0 15rpx;
				margin-top: 6rpx;
				font-size: 24rpx;
				align-self: flex-start;
				border-radius: 4rpx;
				color: #888;
				background-color: #f7f7f8;
			}

			.price {
				display: flex;
				margin-top: 6rpx;
				font-size: 24rpx;
			}

			.symbol {
				font-size: 20rpx;
			}

			.original {
				color: #999;
				text-decoration: line-through;
			}

			.actual {
				margin-left: 10rpx;
				color: #444;
			}

			.text {
				font-size: 22rpx;
			}

			.quantity {
				position: absolute;
				bottom: 0;
				right: 0;
				font-size: 24rpx;
				color: #444;
			}

			.action {
				display: flex;
				flex-direction: row-reverse;
				justify-content: flex-start;
				padding: 30rpx 0 0;

				.button {
					width: 200rpx;
					height: 60rpx;
					text-align: center;
					justify-content: center;
					line-height: 60rpx;
					margin-left: 20rpx;
					border-radius: 60rpx;
					border: 1rpx solid #ccc;
					font-size: 26rpx;
					color: #444;
				}

				.primary {
					color: #27ba9b;
					border-color: #27ba9b;
				}
			}
		}

		.total {
			line-height: 1;
			font-size: 26rpx;
			padding: 20rpx 0;
			color: #666;

			.row {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 10rpx 0;
			}

			.symbol::before {
				content: '¥';
				font-size: 80%;
				margin-right: 3rpx;
			}

			.primary {
				color: #cf4444;
				font-size: 36rpx;
			}
		}
	}

	.detail {
		line-height: 1;
		padding: 30rpx 20rpx 0;
		margin: 20rpx 20rpx 0;
		font-size: 26rpx;
		color: #666;
		border-radius: 10rpx;
		background-color: #fff;

		.title {
			font-size: 30rpx;
			color: #444;
		}

		.row {
			padding: 20rpx 0;

			.item {
				padding: 10rpx 0;
				display: flex;
				align-items: center;
			}

			.copy {
				border-radius: 20rpx;
				font-size: 20rpx;
				border: 1px solid #ccc;
				padding: 5rpx 10rpx;
				margin-left: 10rpx;
			}
		}
	}

	.toolbar-height {
		height: 50rpx;
		box-sizing: content-box;
	}

	.toolbar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: calc(var(--window-bottom));
		z-index: 1;

		height: 100rpx;
		padding: 0 20rpx;
		display: flex;
		align-items: center;
		flex-direction: row-reverse;
		border-top: 1rpx solid #ededed;
		border-bottom: 1rpx solid #ededed;
		background-color: #fff;
		box-sizing: content-box;

		.button {
			display: flex;
			justify-content: center;
			align-items: center;

			width: 200rpx;
			height: 72rpx;
			margin-left: 15rpx;
			font-size: 26rpx;
			border-radius: 72rpx;
			border: 1rpx solid #ccc;
			color: #444;
		}

		.delete {
			order: 4;
			color: #cf4444;
		}

		.button {
			order: 3;
		}

		.secondary {
			order: 2;
			color: red;
			border-color: red;
		}

		.primary {
			order: 1;
			color: #fff;
			background-color: red;
		}
	}

	.popup-root {
		padding: 30rpx 30rpx 0;
		border-radius: 10rpx 10rpx 0 0;
		overflow: hidden;

		.title {
			font-size: 30rpx;
			text-align: center;
			margin-bottom: 30rpx;
		}

		.description {
			font-size: 28rpx;
			padding: 0 20rpx;

			.tips {
				color: #444;
				margin-bottom: 12rpx;
			}

			.cell {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 15rpx 0;
				color: #666;
			}

			.icon::before {
				content: '\e6cd';
				font-family: 'canting' !important;
				font-size: 38rpx;
				color: #999;
			}

			.icon.checked::before {
				content: '\e6cc';
				font-size: 38rpx;
				color: red;
			}
		}

		.footer {
			display: flex;
			justify-content: space-between;
			padding: 30rpx 0 40rpx;
			font-size: 28rpx;
			color: #444;

			.button {
				flex: 1;
				height: 72rpx;
				text-align: center;
				line-height: 72rpx;
				margin: 0 20rpx;
				color: #444;
				border-radius: 72rpx;
				border: 1rpx solid #ccc;
			}

			.primary {
				color: #fff;
				background-color: red;
				border: none;
			}
		}
	}
</style>